<template>
  <div class="product-list">
    <!-- 添加按钮、模糊搜索、查询按钮 -->
    <div class="search">
      <div>
        <el-button @click="toAdd" class="btn" type="primary">添加</el-button>
      </div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item>
          <el-input
            clearable
            v-model="searchForm.name"
            placeholder="请输入产品名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-select
            clearable
            v-model="searchForm.status"
            placeholder="请选择状态"
          >
            <el-option label="正常" value="正常"></el-option>
            <el-option label="下架" value="下架"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            clearable
            v-model="searchForm.productCategoryId"
            placeholder="请选择栏目"
          >
            <el-option
              v-for="item in categoryData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="toSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格数据展示 -->
    <div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column type="index" label="序号"> </el-table-column>
        <el-table-column prop="id" label="产品编号"> </el-table-column>
        <el-table-column prop="name" label="名称"> </el-table-column>
        <el-table-column label="图片" width="70" align="center">
          <template slot-scope="scope">
            <el-image
              style="width: 50px; height: 30px"
              :src="scope.row.photo"
              :preview-src-list="[scope.row.photo]"
            >
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" align="center">
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- <el-tag v-if="scope.row.status ==='正常'" type="success">
              {{scope.row.status}}
            </el-tag>
            <el-tag v-else type="danger">
              {{scope.row.status}}
            </el-tag> -->
            <!-- 优化代码 -->
            <el-tag :type="scope.row.status === '正常' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="category.name" label="所属栏目">
        </el-table-column>
        <el-table-column label="操作" width="130">
          <template slot-scope="scope">
            <el-button @click="toEdit(scope.row)" type="text" size="small"
              >编辑</el-button
            >
            <!-- <el-button v-if="scope.row.status==='下架'" @click="toOnline(scope.row.id)" type="text" size="small">上架</el-button>
          <el-button v-else @click="toOffline(scope.row.id)" type="text" size="small">下架</el-button>
 -->
            <el-button
              :disabled="scope.row.status === '正常'"
              @click="toOnline(scope.row.id)"
              type="text"
              size="small"
              >上架</el-button
            >
            <el-button
              :disabled="scope.row.status === '下架'"
              @click="toOffline(scope.row.id)"
              type="text"
              size="small"
              >下架</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="page-div">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.page"
        :page-sizes="[5, 10, 15, 20, 30]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 添加产品信息对话框 -->
    <div>
      <!-- :before-close="toClose" -->
      <el-dialog :title="title" :visible.sync="visible" @close="toClose">
        <!-- {{form}} -->
        <el-form :model="form" :rules="rules" ref="ruleForm">
          <el-form-item
            prop="name"
            label="产品名称"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            prop="productCategoryId"
            label="所属栏目"
            :label-width="formLabelWidth"
          >
            <el-select
              v-model="form.productCategoryId"
              placeholder="请选择所属栏目"
            >
              <el-option
                v-for="item in categoryData"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="price" label="价格" :label-width="formLabelWidth">
            <el-input v-model.number="form.price" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item prop="photo" label="封面" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              :action="uploadFileURL"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item
            prop="description"
            v-model="form.description"
            label="产品描述"
            :label-width="formLabelWidth"
          >
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="form.description"
            >
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="toSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { pageQuery } from "@/api/productCategory";
//重命名
import {
  pageQuery as pageQueryPro,
  saveOrUpdate,
  offline,
  online,
} from "@/api/product";
import { showFileURL, uploadFileURL } from "@/utils/config";
export default {
  data() {
    return {
      showFileURL,
      uploadFileURL,
      //模糊搜索表单的数据
      searchForm: {
        name: "",
        status: "",
        productCategoryId: "",
      },
      //产品栏目的数据，页面一加载就发请求，请求所有的栏目数据，设置到categoryData
      categoryData: [],
      //表格展示的数据
      tableData: [],
      //分页参数
      params: {
        page: 1,
        pageSize: 10,
      },
      // 总条数
      total: 0,
      //加载
      loading: false,
      //对话框的显示与隐藏
      visible: false,
      //对话框表单的数据
      form: {},
      //表单控件标题的宽度
      formLabelWidth: "80px",
      //对话框的标题
      title: "",
      //图片url
      imageUrl: "",
      // 校验规则
      rules: {
        name: [{ required: true, message: "请输入产品名称", trigger: "blur" }],
        productCategoryId: [
          { required: true, message: "请输入所属栏目", trigger: "change" },
        ],
        price: [
          { required: true, message: "请输入产品价格", trigger: "blur" },
          { type: "number", message: "价格必须为数字", trigger: "blur" },
        ],
        photo: [
          { required: true, message: "请上传封面图片", trigger: "change" },
        ],
      },
    };
  },
  watch: {
    // 深度监听分页参数
    params: {
      handler() {
        this.queryData();
      },
      deep: true,
    },
  },
  created() {
    //页面一加载就调用这个方法发送请求
    this.querycategoryData();
    this.queryData();
  },
  methods: {
    //获取产品分类数据
    async querycategoryData() {
      let res = await pageQuery({
        page: 1,
        pageSize: 100,
      });
      // console.log(res);
      //把请求到的所有的栏目数据，设置到categoryData数组中
      this.categoryData = res.data.list;
    },
    //分页模糊获取产品数据
    /*合并对象
       let obj = {
        ...this.params,
        ...this.searchForm
      } */

    async queryData() {
      this.loading = true;
      //处理数据
      let temp = {
        ...this.params,
        ...this.searchForm,
      };
      //删除对象属性，首先遍历对象，拿到属性值，判断属性值是否为空，若为空则删除
      //temp[key]拿到的是temp里面的属性的属性值
      //temp.key拿到的是temp里面的属性:page、pageSize、name、status、productCategoryId
      for (let key in temp) {
        if (!temp[key]) {
          delete temp[key];
        }
      }
      let res = await pageQueryPro(temp);
      // 加载完毕，关闭加载转圈圈
      this.loading = false;
      this.tableData = res.data.list;
      this.total = res.data.total;
    },
    //查询按钮点击事件处理程序
    toSearch() {
      this.queryData();
    },
    //每页显示的条数发生变化时的事件处理程序
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      /* this.params.pageSize = val;
        this.params.page = 1; */
      this.params = {
        page: 1,
        pageSize: val,
      };
    },
    // 当前页码发生变化时的事件处理程序
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.params.page = val;
    },
    //添加按钮事件处理程序
    toAdd() {
      this.querycategoryData();
      // 在对话框再次打开时清空表单数据
      this.form = {};
      this.imageUrl = "";
      this.title = "添加产品信息";
      this.visible = true;
    },
    //图片上传成功的回调函数
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      // this.form.photo = showFileURL + res.data.id;
      // 从图片服务器请求图片路径存到表单
      this.form.photo = file.response;
    },
    //图片上传之前的回调函数
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //对话框确定按钮事件处理程序
    toSave() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          // 校验通过，做保存
          // console.log("校验通过");
          let res = await saveOrUpdate(this.form);
          // 提示用户保存成功，刷新表格数据，关闭对话框
          this.$notify.success({
            title: "保存成功",
            message: res.message,
          });
          //刷新数据就是重新请求数据,调用请求方法
          this.queryData();
          // this.toClose();
          this.visible = false;
        } else {
          // 校验不通过
          return false;
        }
      });
    },
    // 关闭对话框
    toClose() {
      // 重置表单验证
      this.$refs.ruleForm.resetFields();
      // 超时调用，超过时间再去调用，即等表单验证重置之后再关闭对话框
      /* setTimeout(()=>{
          this.visible= false;
        },500); */
    },
    // 编辑按钮
    toEdit(row) {
      this.querycategoryData();
      // 设置表单数据
      this.form = { ...row };
      this.imageUrl = this.form.photo;
      this.title = "编辑产品信息";
      this.visible = true;
    },
    //上架按钮
    async toOnline(id) {
      let res = await online({ id });
      this.$notify.success({
        title: "上架成功",
        message: res.message,
      });
      // 调用这个方法重新请求数据起到刷新数据作用
      this.queryData();
    },
    //下架按钮
    async toOffline(id) {
      let res = await offline({ id });
      this.$notify.success({
        title: "下架成功",
        message: res.message,
      });
      // 调用这个方法重新请求数据起到刷新数据作用
      this.queryData();
    },
  },
};
</script>

<style lang="scss" scoped>
/* .product-list{
  padding: 10px;
} */
.search {
  display: flex;

  // height: 40px;
  .btn {
    margin-right: 10px;
  }
}
</style>
